function nav_template(){/*
<a class="btn btn-primary btn{appid}" href="./show-app.php?appid={appid}" title="{des}">
  {name}
</a>
*/}

function search_app_template(){/*
<div><a class="btn btn-primary btn{appid}" style="color:white;text-align:left;width:200px;word-wrap:break-word; word-break:break-all;"
  href="./show-app.php?appid={appid}" target="_blank" title="{des}">
  {name}
  <p text-muted>{des}</p>
</a></div>
*/}

function app_template(){/*
<div class=" col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="panel panel-primary skin{skin}">
  <div class="panel-heading">
    <h3 class="panel-title"><a href="./show-app.php?appid={appid}" target="_blank" title="{des}">
      {name}<span class="lang-shortcut">快捷键</span>
    </a></h3>
  </div>
  <div class="panel-body text-center" style="height:160px;overflow:hidden">
    <a class="" href="./show-app.php?appid={appid}" title="{des}" target="_blank">
    <img style='max-width:128px;_width:expression(this.width > 128 ? "128px" : this.width);' src="{logo}" />
    </a>
  </div>
  <div class="panel-footer text-right">
      <a href="export.php?appid={appid}" target="_blank"
        class="lang-export edit-item">导出</a>
      <a href="edit-app.php?appid={appid}" target="_blank"
        class="lang-edit edit-item">编辑</a>
      <a href="theme.php?appid={appid}" target="_blank"
        class="lang-theme-paper edit-item">壁纸</a>
      <a class="lang-proceed btn btn-success" href="./show-app.php?appid={appid}" target="_blank">前往</a>
  </div>
</div>
</div>
*/}


function add_app_template(){/*
<div class=" col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="panel panel-primary skin{skin}">
  <div class="panel-heading">
    <h3 class="panel-title"><a href="./add-app.php" target="_blank" title="{des}">
      {name}
    </a></h3>
  </div>
  <div class="panel-body" style="height:160px;overflow:hidden">
    <p class="text-center"><a href="./add-app.php" title="{des}" target="_blank">
    <img style='max-width:128px;_width:expression(this.width > 128 ? "128px" : this.width);' src="{logo}" />
    </a></p>
  </div>
  <div class="panel-footer text-right"> 
    <a class="lang-proceed-add btn btn-success" href="./add-app.php" target="_blank">前往添加</a>
  </div>
</div>
</div>
*/}

function is_matched(key, data){
  var tmp =data['name'].toLowerCase();
  var pkey = data['shortcut'];
  var lpkey = pkey.toLowerCase();
  if((tmp.localeCompare(key) == 0)
    || tmp.indexOf(key) != -1
    || (data.pinyin.indexOf(key) != -1)
    || lpkey.indexOf(key) != -1
    || (pkey.indexOf(key) != -1)){
    return true;
  }
  return false;
}



function is_app_matched(key, data){
  var tmp =data['name'].toLowerCase();
  var pkey = data['des'];
  var lpkey = pkey.toLowerCase();
  if((tmp.localeCompare(key) == 0)
    || tmp.indexOf(key) != -1
    || (data.pinyin.indexOf(key) != -1)
    || lpkey.indexOf(key) != -1
    || (pkey.indexOf(key) != -1)){
    return true;
  }
  return false;
}

//搜索结果
function search_data(key)
{
  key =$.trim(key).toLowerCase();
  if(key == "") return;
  var s ="";
  var template = hereDoc(search_template);
  var template_edit_item = hereDoc(edit_item_template);
  for (var t in all_data){
    var data_list = all_data[t].datalist;
    for(var i in data_list){
      data = data_list[i];
      if (is_matched(key, data)){
        s += nano(template, data);
        s += nano(template_edit_item, data);
      }
    }
  }
  return s;
}

var all_data = {};
var all_data_list = [];
var gInfo = {};
var gStr = {};

function get_all_callback(appid, d) {
  // 处理多语言的情况
  var all_app = 'all-app';
  var all_shortcut = 'all-shortcut';
  var one_app = 'one-app';
  var comment_count = 'comment-count';
  if (!d[all_app]) all_app = 'all-app-en';
  if (!d[all_shortcut]) all_shortcut = 'all-shortcut-en';
  if (!d[comment_count]) comment_count = 'comment-count';

  gCommentCount = d[comment_count];

  get_category_callback(appid, d[one_app]);
  get_item_callback(appid, d[all_shortcut]);
  get_info_callback(appid, {});
}


function get_page(appid, lang){
  all_data = {};
  all_data_list = [];

  if (!lang) lang = 'cn';
  var u='query.php?op=all&appid='+appid+'&lang='+lang;
  $.ajax({url:u,
      //dataType:"json",
      async:true,
      success : function(msg, textStatus) { 
        gAppID = appid;
        var pos = msg.indexOf('{');
        if (pos >= 0) {
          msg = msg.substring(pos);
        }
        eval('msg='+msg);
        get_all_callback(appid, msg);

        var theme = getInfo(appid, 1);
        var mode = getInfo(appid, 2); // 模式
        change_theme(theme, mode);
      }
  },"text");
}

function change_theme(theme, mode){
  // 确定是否需要载入主题
  var jsname = "./js/theme-"+theme+".js"
  $.getScript(jsname, function(){
    gen_page(gAppID, mode);
    setInfo(gUserID, 1, theme);
    theme_finally();
  }); 

}

function get_apps_callback(appid, m){
  var s = hereDoc(nav_template);
  var r = "";
  for (var i in m) {
    var data = m[i];
    data.name = encodeHtml(data.name);
    data.des = encodeHtml(data.des);
    r += nano(s, data);
  }
  
  r = '<ul class="nav nav-pills ">' + r + '</ul>';
  $("#nav-content").html(r);
}

function get_category_callback(appid, d){
  for (var i in d) {
    var data = d[i];
    $(document).attr("title", data.name+gLangData['lang-shortcut']);//修改title值
    data.name = encodeHtml(data.name);
    //data.des = encodeHtml(data.des);
    data.des = getMarkdown(data.des);
    all_data[data.appid] = {};
    all_data[data.appid].datalist = [];
    all_data[data.appid].info = data;
  }

}

function reorder(d, s) {
  R = [];
  T = [];
  M = {};

  L = new String(s).split(' ');
  for (var i in L) {
    var x = L[i];
    if (d.hasOwnProperty(x)) {
      R.push(x);
      M[x] = 1;
    }
  }

  for (var x in d) {
    if (M.hasOwnProperty(x)) {
      continue;
    } else {
      R.push(x);
    }
  }
  return R;
}

function get_item_callback(appid, d){
  try{
  all_data[appid].datalist = d;
  }catch(e){
  }
}

function get_info_callback(appid, d){
  getInfo(appid, 1);
  getInfo(appid, 2);
  //for (var i in d) {
  //  var k = parseInt(d[i].id);
  //  var v = parseInt(d[i].value);
  //  gInfo[k] = v;
  //}
}


function get_comment_count_callback(appid, d){
  for (var i in d) {
    var data = d[i];
    data.appid = appid;
    var sID = nano("#sns-{appid}-{shortcutid} .count", data);
    var count = data.count;
    $(sID).text(count);
  }
}


function get_str_callback(appid, d){
  for (var i in d) {
    var k = parseInt(d[i].id);
    var v = d[i].value;
    if (!v) v = "";
    gStr[k] = v;
  }
}

//------------------------------------------
//
//
//

function getStr(appid, id) {
  var k = parseInt(id);
  if(gStr[k]){
    return gStr[k];
  }
  return "";
}

function setStr(appid, id, v) {
  var k = parseInt(id);
  v = new String(v).valueOf();
  gStr[k] = v;
  var u = 'update-data.php';
  var data = {
    appid:appid,
    id:k,
    value:v,
    op:"set-str"
  };

  $.post("update-data.php", data,function(msg){
  }); 

  return v;
}

function getInfo(appid, id) {
  var k = parseInt(id);
  if(gInfo[k]){
    return gInfo[k];
  }
  var v = $.cookie(new String(id));
  v = parseInt(v);
  if (v) {
    gInfo[k] = v;
    return v;
  }
  return 0;
}

function setInfo(appid, id, v) {
  var k = parseInt(id);
  v = parseInt(v);
  gInfo[k] = v;
  $.cookie(new String(id), v, 3600*24*7);

  //var u = 'update-data.php';
  //var data = {
  //  appid:appid,
  //  id:k,
  //  value:v,
  //  op:"set-info"
  //};

  //$.post("update-data.php", data,function(msg){
  //}); 

  return v;
}

//------------------------------------------
function do_collect(appid, id, op){
  var data = {
    appid:appid,
    id:id,
    op:op
  };

  var upID = nano('#up-{appid}-{shortcutid}',{'appid':appid, 'shortcutid':id})
  var downID = nano('#down-{appid}-{shortcutid}',{'appid':appid, 'shortcutid':id})

  $(upID).attr("disabled",true);
  $(downID).attr("disabled",true);

  $.ajax({url:"query.php",
    async:true,
    data:data,
    success : function(msg, textStatus) { 
      eval("d="+msg);
      var down = d[0]['down'];
      var up = d[0]['up'];
      
      $(downID+" .count").html(down);
      $(upID+" .count").html(up);
  }
  });

}
function do_down(appid, id) {
  do_collect(appid, id, 'inc-down');
}


function do_up(appid, id) {
  do_collect(appid, id, 'inc-up');
}


// -----------------------------------------------------------

function sns_template(){/*
<div class="">
  <div>{content}</div>
  <div class="text-muted">{update_time}</div>
</div>
*/}


function toggle_sns(appid, shortcutid){
  var sID = nano("#sns-panel-{appid}-{shortcutid}", {'shortcutid':shortcutid, 'appid':appid});
  $(sID).toggleClass("hide");
  if ($(sID).is(":visible")){
    get_sns_data(appid, shortcutid);
  }
};


function send_sns(appid, shortcutid){
  var sID = nano("#sns-panel-{appid}-{shortcutid}", {'shortcutid':shortcutid, 'appid':appid});
  var sns_content = $(sID + " .sns-content").val();
  if(sns_content.length < 3){
    show_msg(sID + " .sns-msg", "too short");
    return;
  }
  if(sns_content.length > 140){
    show_msg(sID + " .sns-msg", "too long");
    return;
  }

  var data = {
    op:'add-sns',
    id:shortcutid,
    appid:appid,
    userid:gUserID,
    content:sns_content,
    parent:0,
    status:0
  };

  show_msg(sID + " .sns-msg", "提交中...");
  $.post("update-data.php", data, function(msg){
    $(sID+" .sns-msg").html(gLangData['lang-send-succeed']);

    data.update_time = new Date().toLocaleString();

    var s = hereTemplate(sns_template, data);
    $(s).appendTo($(sID + " .sns-result"));
    $(sID + " .sns-content").val("");

    var snsCountID = nano("#sns-{appid}-{shortcutid} .count", {'shortcutid':shortcutid, 'appid':appid});
    var snsCount = $(snsCountID).html();
    snsCount = parseInt(snsCount) + 1;
    $(snsCountID).html(snsCount);

    show_msg(sID + " .sns-msg", "Done");
  });

  return;
}


function get_sns_data(appid, shortcutid){
  var sID = nano("#sns-panel-{appid}-{shortcutid}", {'shortcutid':shortcutid, 'appid':appid});
  var u = 'query.php?op=get-sns-by-shortcut&id='+shortcutid+'&appid='+appid;
  $.ajax({url:u,
    dataType:"json",
    async:true,
    success : function(msg, textStatus) {
      var L = msg;
      var R = "";
      if(L){
        for(var i in L){
          var data = L[i];
          var s = hereDoc(sns_template);
          s = nano(s, data);
          R += s;
        }
      }
      $(sID + " .sns-result").html(R);
    }
  },"text");
}



// -----------------------------------------------------------







function gen_page(appid){
  //默认为0
  var mode = getInfo(appid, 2);
  var theme = getInfo(appid, 1);

  var result = ""
  var template_url = hereDoc(url_template);
  var template_edit_item = hereDoc(edit_item_template);
  var template_item = template_url;
  var template_column = hereDoc(column_template);
  var COLUMN_COUNT = 6;
  var icol = 0;
  var s = getStr(appid, 1);
  var R = reorder(all_data, s);
  for(var j in R){
    var t = R[j];
    var data_list = all_data[t].datalist;
    var data_size = data_list.length;
    var head = all_data[t].info.name;
    var des = all_data[t].info.des;
    var id = all_data[t].info.appid;
    var logo = all_data[t].info.logo;
    var hrefs = "";
    var count = 0;

    for(var i in data_list){
      var data=data_list[i];
      data.appid = appid;

      data.i = count + 1;
      var s = nano(template_item, data);
      hrefs += s;
      count += 1;

      if (!data.name) data.name = "";
      data.pinyin = hanzi_to_pinyin(data.name).toLowerCase();
      all_data_list.push(data);
    }
    
    var data={"head":head,"hrefs":hrefs, 
      "id":appid, "des":des, "appid":appid,
      "mode":getInfo(appid, 2),"logo":logo};
    result += nano(template_column, data);
    icol += 1;
    if (icol == COLUMN_COUNT) {
      result += '<div class="clearfix"></div>';
      icol = 0;
    }
  }


  $("#result").html(result);


  var theme = getInfo(appid, 1);
  if (theme != 0) theme = 1;//现在只有两种 TODO
  // 更新classic

  $(".skin1").addClass("list-group-item-danger");
  $(".skin2").addClass("list-group-item-info");
  $(".skin3").addClass("list-group-item-warning");
  $(".skin4").addClass("list-group-item-success");


  //添加自动提示
  var s = "";
  var arr=[];
  
  $("#autocomplete").autocomplete({
   minLength: 1,
   source:  function(request, response) {
    var result_list = [];
    var key = request.term.toLowerCase();
    for(var i = 0; i < all_data_list.length; i++){
      var data = all_data_list[i];
      if (is_matched(key, data)){
          result_list.push(data);
      }
      
      var SHOW_SIZE = 9;
      // 只提示前面的
      if (result_list.length > SHOW_SIZE) {
          break;
      }
    }
    response(result_list);
  },
  focus: function(event, ui) {
    $("#autocomplete").val(ui.item.name);
    return false;
  },
  select: function(event, ui) {
    $("#autocomplete").val(ui.item.name);
    return false;
  }
  })
  .autocomplete("instance")._renderItem = function(ul, item) {
    var template = hereDoc(search_item_template);
    item.appid = appid;
    return $(nano(template, item))
      .appendTo(ul);
  };

  //回车
  $("#autocomplete").unbind('keyup').keyup(function(event){
    if(event.keyCode == 13 || event.keyCode == 10){
      $("#go").trigger("click");
    }
  });
  
  //添加搜索
  $("#go").unbind('click').click(function(){
    var key =$("#autocomplete").val();
    var s = search_data(key);
    $("#search-result").html(s);
  });
  
  //清除结果
  $("#clear").unbind('click').click(function(){
    $("#autocomplete").val("");
    $("#search-result").html("");
    $("#autocomplete").focus();
  });

  $("#edit").unbind('click').click(function(){
    $(".edit-func").toggle();
  });

  $("#order-text").val(getStr(appid, 1));
  $("#theme-text").val(getInfo(appid, 1));
  $("#mode-text").val(getInfo(appid, 2));
  $(".btn"+appid).addClass('btn-success'); 
  switch_lang(gLang);
  get_comment_count_callback(appid, gCommentCount);
  //$(".collapse").collapse();
}

/**
 * 生成主页的软件列表
 */
function gen_home_page(){

  var result = ""
  var template_item = hereDoc(app_template);
  var COLUMN_COUNT = 6;
  var count = 0;

  for(var i in gAllApp){
    var data=gAllApp[i];
    data.i = count + 1;
    var s = nano(template_item, data);
    count += 1;

    if (!data.name) data.name = "";
    data.pinyin = hanzi_to_pinyin(data.name).toLowerCase();
    all_data_list.push(data);
    result += s;
  }

  var dataAdd = {
    appid: "0",
    des: "添加新的软件",
    i: 0,
    logo: "http://www.easyicon.net/api/resizeApi.php?id=1187494&size=128",
    name: "Add New",
    pinyin: "Add New",
    skin: "0"
  };
  var s = hereTemplate(add_app_template, dataAdd);
  //result=s+result;
  
  $("#result").html(result);

  $(".skin1").addClass("panel-danger");
  $(".skin2").addClass("panel-info");
  $(".skin3").addClass("panel-warning");
  $(".skin4").addClass("panel-success");
  $(".skin5").addClass("panel-default");


  //添加自动提示
  var s = "";
  var arr=[];
  
  $("#autocomplete").autocomplete({
   minLength: 1,
   source:  function(request, response) {
    var result_list = [];
    var key = request.term.toLowerCase();
    for(var i = 0; i < all_data_list.length; i++){
      var data = all_data_list[i];
      if (is_app_matched(key, data)){
          result_list.push(data);
      }
      
      var SHOW_SIZE = 9;
      // 只提示前面的4个
      if (result_list.length > SHOW_SIZE) {
          break;
      }
    }
    response(result_list);
  },
  focus: function(event, ui) {
    $("#autocomplete").val(ui.item.name);
    return false;
  },
  select: function(event, ui) {
    $("#autocomplete").val(ui.item.name);
    return false;
  }
  })
  .autocomplete("instance")._renderItem = function(ul, item) {
    var template = hereDoc(search_app_template);
    return $(nano(template, item))
      .appendTo(ul);
  };

  //回车
  $("#autocomplete").unbind('keyup').keyup(function(event){
    if(event.keyCode == 13 || event.keyCode == 10){
      $("#go").trigger("click");
    }
  });
  
  //添加搜索
  $("#go").unbind('click').click(function(){
    var key =$("#autocomplete").val();
    var s = search_data(key);
    $("#search-result").html(s);
    $("#autocomplete").focus();
  });
  
  //清除结果
  $("#clear").unbind('click').click(function(){
    $("#autocomplete").val("");
    $("#search-result").html("");
    $("#autocomplete").focus();
  });

  switch_lang(gLang);
}


$(function(){
  $("#switch-lang").unbind('click').click(function(){
    if(gLang == "en"){
      gLang = "cn";
    } else {
      gLang = "en";
    }
    switch_lang(gLang);
  });


  Mousetrap.bind('j', function() { //向下滚动
    $("html, body").stop(true, true).animate({'scrollTop':"+=200px"}, 300);
  });
  Mousetrap.bind('k', function() { //向上滚动
    $("html, body").stop(true, true).animate({'scrollTop':"-=200px"}, 300);
  });
  Mousetrap.bind('g g', function() { //到达顶部
    $("html, body").stop(true, true).animate({'scrollTop':"0"}, 300);
  });
  Mousetrap.bind('G', function() { //到达底部
    $("html, body").stop(true, true).animate({'scrollTop':$(document).height()}, 300);
  });
  Mousetrap.bind('/', function() { //搜索
    $("#clear").trigger('click');
  });
  Mousetrap.bind('esc', function() { //搜索
    $("#autocomplete").blur();
  });

})

var gLang = "cn";
var gAllApp = [];
var gCommentCount = {};
var gUserID = 5012111;
var gAppID = 2;